import {
	createStore
} from 'vuex'

import wkstate from "./module/work-state.js";
import user from "./module/user.js";

import s3d from "./cfg.js";

import {
	ElMessage
} from "element-plus";


// 尝试修改
var _h = -1;
import callApi from "@/api/proj.js";
//触发事件
//state 中的值在 action 中无法更改
export default createStore({
	state: {
		//电表
		dian:false,
		//水表
		shui:false,
		//监控列表
		motiorNum:[],
		//监控设备详细信息
		monitorDevices: {
			list: [],       // 所有监控设备列表
			byId: {},       // 按ID索引的监控设备
			byBuilding: {}, // 按建筑分组的监控设备
			byType: {},     // 按类型分组的监控设备
			byCode: {}      // 按code索引的监控设备
		},
		//门禁
		door:false,
		//监控
		motior:true,
		//闸机人脸
		face:false,
		title: document.title,
		pageCache: [], //缓存子页 
		pgCurrent: "", //当前页		
		isFullScene: false, //场景全屏
		showHead: true, //头显示
		showAside: true, //两侧显示

		headHeight: "60px", //头高
		asideWidth: '420px', //两侧宽度		
		footerHeight: '30px', //脚高
		query: {}, //参数
		test: false, //页面开发阶段

		year: new Date().getFullYear(),
		spaceComd: {},
		spaceComds: ["a", "b", "c"],

		api: callApi(),

		engrgy: {},
		alarm: {},
		menuItem2: null,
		allDevs: [],
		arrAir: [], //空调列表
		arrAirStates: [], //空调运行状态
	},
	getters: {
		//获取电表状态
		dian: (s) => {
			return s.dian;
		},
		//获取水表状态
		shui: (s) => {
			return s.shui;
		},
		//获取监控列表
		motiorNum: (s) => {
			return s.motiorNum;
		},
		//获取门禁状态
		door: (s) => {
			return s.door;
		},
		//获取监控状态
		motior: (s) => {
			return s.motior;
		},
		//获取闸机人脸状态
		face: (s) => {
			return s.face;
		},
		pages: (s) => {
			return s.pageCache.map(t => t.name);
		},
		api: (s) => {
			return s.api;
		},
		// 获取按类型分组的监控设备
		monitorDevicesByType: state => typeId => 
			state.monitorDevices.byType[typeId] || [],
		
		// 获取监控设备总数
		monitorDevicesCount: state => state.monitorDevices.list.length,
		
		// 根据code获取监控设备
		getMonitorByCode: state => code => state.monitorDevices.byCode[code] || null,
		
		// 根据code获取SXTJSON
		getSXTJSONByCode: state => code => {
			const device = state.monitorDevices.byCode[code];
			return device ? device.SXTJSON : null;
		},
		// 根据ID获取监控设备
		monitorDeviceById: state => id => {
			// 先尝试从byId中获取
			if (state.monitorDevices.byId[id]) {
				return state.monitorDevices.byId[id];
			}
			
			// 如果没找到，尝试在list中查找
			return state.monitorDevices.list.find(device => 
				device.ID === id || 
				device.id === id || 
				device.devId === id
			) || null;
		},
		
		// 获取按建筑分组的监控设备
		monitorDevicesByBuilding: state => buildingId => 
			state.monitorDevices.byBuilding[buildingId] || [],
		
		// 获取所有modelType为1的设备
		getModelType1Devices: state => {
			return state.monitorDevices.list.filter(device => device.modelType === 1);
		},
		
		// 获取特定modelType的设备
		getDevicesByModelType: state => modelType => {
			return state.motiorNum.filter(device => device.modelType === modelType);
		},
	},
	actions: {
		//修改电表状态
		updateDian({ commit }, value) {
			commit('dian', value);
		},
		//修改水表状态
		updateShui({ commit }, value) {
			commit('shui', value);
		},
		//修改监控数量
		updateMotiorNum({ commit }, value) {
			commit('motiorNum', value);
		},
		// 更新监控设备信息
		updateMonitorDevices({ commit }, devices) {
			commit('updateMonitorDevices', devices);
		},
		//修改门禁状态
		updateHSetDoor({ commit }, value) {
			commit('hSetDoor', value);
		  },
		  //修改监控状态
		  updateHSetMotior({ commit }, value) {
			commit('hSetMotior', value);
		  },
		  //修改闸机人脸状态
		  updateHSetFace({ commit }, value) {
			commit('hSetFace', value);
		  },
		asyncBegin(store, t) {
			store.dispatch("asyncInitDat", '');
		},
		asyncDevInfo(store, devid) {
			return store.getters.api.engrgy.getSubDev(devid);
		},
		getSceneDev(store, code) {
			return new Promise((resolve, reject) => {
				let d = store.state.allDevs.find((t => t.SXTJSON == code));
				console.log("find", d);
				if (d) {
					resolve(d);
				} else {
					ElMessage.warning("该设备无法定位,请确认场景是否初始化完成，且已添加" + code);
				}
			});
		},
	},
	mutations: {
		//电表修改
		dian(s, i) {
			s.dian = i;
		},
		//水表修改
		shui(s, i) {
			s.shui = i;
		},
		//监控数量修改
		motiorNum(s, i) {
			s.motiorNum = i;
		},
		//门禁修改
		hSetDoor(s, i) {
			s.door = i;
		},
		//监控修改
		hSetMotior(s, i) {
			s.motior = i;
		},
		//闸机人脸修改
		 hSetFace(s, i) {
			s.face = i;
		},

		hSetMenuItem2(s, i) {
			// 菜单的 子菜单事件
			s.menuItem2 = i;
		},
		hSetAir(s, dat) {
			s.arrAir = dat;
			let arr = []
			dat?.list?.forEach(air => {
				arr.push({
					...air,
					run: air.statusName != "关机"
				});
			});

			let state = [];
			s.allDevs.forEach(d => {
				arr.forEach(air => {
					if (d.SXTJSON == air.devnum) {
						state.push({
							ID: d.ID,
							run: air.run + "",
							wendu: air.szwd || 26
						})
					};
				})
			});
			s.arrAirStates = state;
			//console.log("空调状态1,", state);
		},
		// hSetAllDevs(s, i) {
		// 	s.allDevs = i;
		// 	let airDats = s.arrAir.list;
		// 	let arr = []
		// 	airDats.forEach(air => {
		// 		arr.push({
		// 			...air,
		// 			run: air.statusName != "关机"
		// 		});
		// 	});

		// 	let state = [];
		// 	s.allDevs.forEach(d => {
		// 		arr.forEach(air => {
		// 			if (d.SXTJSON == air.devnum) {
		// 				state.push({
		// 					ID: d.ID,
		// 					run: air.run + "",
		// 					wendu: air.szwd || 26
		// 				})
		// 			};
		// 		})
		// 	});
		// 	s.arrAirStates = state;
		// 	//console.log("空调状态2,", state);
		// },
		hSetEngrgy(s, v) {
			s.engrgy = v;
		},
		// hSetAlarm(s, v) {
		// 	s.alayr = v;
		// },
		hSetSpaceComd(s, vs) {
			s.spaceComds = vs;
			if (vs[0]) {
				s.spaceComd = vs[0];
			}
		},
		hSpaceComdChange(s, v) {
			s.spaceComd = v;
			console.log("空间切换", v);
		},
		hPageOpen(state, page) {
			state.pageCache.push(page);
		},
		hClearCache(state, d) {
			state.pageCache = [];
		},
		hSetPg(s, d) {
			s.pgCurrent = d;
		},
		hSetQuery(s, d) {
			s.query = d;
		},
		hFullScene(s, d) {
			//s.isFullScene = d;
			s.showAside = !d;
			return;
			if (enable) {
				hFullScreen();
			} else {
				hExitFullscreen();
			}
		},
		// 更新监控设备详细信息
		updateMonitorDevices(s, devices) {
			// 存储完整列表
			s.monitorDevices.list = devices;
			
			// 按ID索引
			const byId = {};
			// 按建筑分组
			const byBuilding = {};
			// 按类型分组
			const byType = {};
			// 按code索引
			const byCode = {};
			
			devices.forEach(device => {
				// 按ID索引
				if (device.ID) {
					byId[device.ID] = device;
				}
				
				// 按code索引
				if (device.id) {
					byCode[device.id] = device;
				}
				
				// 按建筑分组
				const buildingId = device.buildingId || 'unknown';
				if (!byBuilding[buildingId]) {
					byBuilding[buildingId] = [];
				}
				byBuilding[buildingId].push(device);
				
				// 按类型分组
				const deviceType = device.modelId || device.typeId || 'unknown';
				if (!byType[deviceType]) {
					byType[deviceType] = [];
				}
				byType[deviceType].push(device);
			});
			
			s.monitorDevices.byId = byId;
			s.monitorDevices.byBuilding = byBuilding;
			s.monitorDevices.byType = byType;
			s.monitorDevices.byCode = byCode;
		},
	},
	modules: {
		user,
		wkstate,
		s3d
	}
})
/**
 * actions 调用方式
 *	store.dispatch("asyncXXX",dat);
 * mutations 调用方式
 *	store.commit("hXXX",dat); 
 * 
 const {
 	needLogin,
 	logined
 } = toRefs(store.state.user);
 
 store.dispatch("s3d/asyncFn","异步查询数据");		 
 store.commit("s3d/hFn","同步修改数据");
 store.getters["s3d/dat"]("获取数据")
 * */